import { onUnmounted } from 'vue';

/**
 * 打开 SSE 连接
 * @param {string} url 完整的请求地址
 * @param {(data: string, done: boolean) => void} onData 数据处理回调
 * @returns {{eventSource: EventSource}}
 */
export function useEventSource(url, onData) {
  const eventSource = new EventSource(url);

  eventSource.onmessage = (event) => {
    const data = event.data;
    const done = data === '[DONE]' || data === 'DONE';
    if (onData) {
      onData(data, done);
    }
    if (done) {
      eventSource.close();
    }
  };

  eventSource.onerror = () => {
    eventSource.close();
  };

  onUnmounted(() => {
    eventSource.close();
  });

  return { eventSource };
} 